
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Apache Tomcat WebSocket Examples: Chat</title>
<style type="text/css">
input#chat {
	width: 410px
}

#console-container {
	width: 400px;
}

#console {
	border: 1px solid #CCCCCC;
	border-right-color: #999999;
	border-bottom-color: #999999;
	height: 170px;
	overflow-y: scroll;
	padding: 5px;
	width: 100%;
}

#console p {
	padding: 0;
	margin: 0;
}
</style>
<script type="application/javascript">
	

////////////////////////////////////////////////////////////////

		//定义一个对象，表示当前应用
        var App = {};
        
        //定义一个变量，用来指向之后的websocket对象
        App.socket = null;

        //定义一个自己的connect函数，参数为websocket的url
        App.connect = (function(host) {
        	//初始化websocket对象，和websocket服务器建立连接
            if ('WebSocket' in window) {
            	App.socket = new WebSocket(host);
            } else if ('MozWebSocket' in window) {
            	App.socket = new MozWebSocket(host);
            } else {
                Console.log('Error: WebSocket is not supported by this browser.');
                return;
            };

            //定义websocket标准规定的几个onXXX回调handler
            App.socket.onopen = function (e) {
            	 onOpen(e);
            };

            App.socket.onclose = function (e) {
				onClose(e);
            };

            App.socket.onmessage = function (message) {
            	onMessage(message)
            };
	
        });
        
        //这个是setInterval的返回值。在onOpen里会调用setInterval，用来发心跳。
        //重连时，会需要先clearInterval，以避免每次重连导致每次增加一个interval执行
        var intervalId;
        
    	function onOpen(event) { 
    		
    		//发送心跳
    		clearInterval(intervalId);
    		intervalId = setInterval(function() {
    		    	App.socket.send("{\"event\":\"ping\"}");
    		  }, 1000);
    		
    		//打日志，具体项目中可去除掉
    	    Console.log('OnOpen: WebSocket connection opened.');
    		//输入框中按回车发送消息
    	    document.getElementById('chat').onkeydown = function(event) {
    	        if (event.keyCode == 13) {
    	        	App.sendMessage(document.getElementById('chat').value);
    	        }
    	    };
    	};
    	
    	function onClose(event) {
    		//1)处理业务
    		Console.log('OnClose: WebSocket closed.');
    	    document.getElementById('chat').onkeydown = null;
    	    //2）重连
    	   	App.initialize();
    	};
    	
    	function onMessage(message) { 
    		Console.log('OnMessage: '+event.data);
    		//1）解析消息，按照event name，获取相应的handler，并调用handler
    		//  xxxxxx
    	};
    	
    	//初始化连接
        App.initialize = (function() {
        	var host = window.location.host;
            if (window.location.protocol == 'http:') {
            	App.connect('ws://' + host + '/ws/websocket/chat/zhangsan');
            } else {
            	App.connect('wss://' + host + '/ws/websocket/chat/zhangsan');
            }
        });

        //可以封装一个自己的sendMessage函数，除了发送消息意外，还可以处理些其他必要的事务，比如更新界面等
        App.sendMessage = (function(message) {
            if (message != '') {
            	//真正调用websocket发送消息
            	App.socket.send(message);
            }
        });
    
////////////////////////////////////////////////////////////////
        var Console = {};

        Console.log = (function(message) {
            var console = document.getElementById('console');
            var p = document.createElement('p');
            p.style.wordWrap = 'break-word';
            p.innerHTML = message;
            console.appendChild(p);
            while (console.childNodes.length > 25) {
                console.removeChild(console.firstChild);
            }
            console.scrollTop = console.scrollHeight;
        });
////////////////////////////////////////////////////////////////
        App.initialize();



</script>
</head>
<body>

	<p>
		<input type="text" placeholder="type and press enter to chat"
			id="chat"></input>
	</p>
	<div id="console-container">
		<div id="console"></div>
	</div>

</body>
</html>